#!/bin/bash

# sealos 官网: https://sealos.io/zh-Hans/docs/self-hosting/lifecycle-management/quick-start/deploy-kubernetes

set -e

# 初始设置
# 升级软件
# yum -y update
# 升级内核
# bash <(curl -sSL https://gitee.com/michelalive/Deploy-repo/raw/master/kernel/upgrade_kernel.sh)
# 各节点初始化
# bash <(curl -sSL https://gitee.com/michelalive/shell_scripts/raw/master/kubernetes/sealos/setEnv.sh)
# master执行
# bash <(curl -sSL https://gitee.com/michelalive/shell_scripts/raw/master/kubernetes/sealos/install_kubernetes.sh) password

# 替换 containerd 配置文件
# rm -f /etc/containerd/config.toml && wget https://gitee.com/michelalive/Deploy-repo/raw/master/kubernetes/sealos/config.toml && mv config.toml /etc/containerd/config.toml && systemctl restart containerd

SEALOS_VERSION="4.3.7"
KUBERNETES_VERSION="v1.27.16"
MASTER_ADDR="192.168.88.10"
NODE_ARRY="192.168.88.11,192.168.88.12"
PASSWORD=$1

# 检查是否提供了密码参数
if [ -z "$PASSWORD" ]; then
    echo "错误：请提供密码参数。"
    echo "用法：$0 <password>"
    exit 1
fi

# 定义 sealos 下载路径和文件名
SEALOS_URL="https://github.com/labring/sealos/releases/download/v${SEALOS_VERSION}/sealos_${SEALOS_VERSION}_linux_amd64.tar.gz"
SEALOS_TAR="sealos_${SEALOS_VERSION}_linux_amd64.tar.gz"
SEALOS_BIN="/usr/local/bin/sealos"

# 检查 sealos 是否已下载
if [ ! -f "$SEALOS_TAR" ]; then
    echo "正在下载 sealos..."
    wget $SEALOS_URL
fi

# 解压并安装 sealos
if [ ! -x "$SEALOS_BIN" ]; then
    echo "正在安装 sealos..."
    tar -zxvf $SEALOS_TAR -C /usr/local/bin/
    chmod +x $SEALOS_BIN
fi

# 检查 sealos 是否成功安装
if [ ! -x "$SEALOS_BIN" ]; then
    echo "错误：sealos 安装失败。"
    exit 1
fi

echo "使用 sealos 部署 Kubernetes..."

$SEALOS_BIN run registry.cn-shanghai.aliyuncs.com/labring/kubernetes:$KUBERNETES_VERSION \
 registry.cn-shanghai.aliyuncs.com/labring/helm:v3.9.4 \
 registry.cn-shanghai.aliyuncs.com/labring/cilium:v1.13.4 \
     --masters $MASTER_ADDR \
     --nodes $NODE_ARRY \
     -p $PASSWORD

echo "Kubernetes 部署完成。"
echo "执行一下命令可配置 kubectl 自动补全"
echo "yum install -y bash-completion "
echo "source /usr/share/bash-completion/bash_completion"
echo "source <(kubectl completion bash)"
echo 'echo "source <(kubectl completion bash)" >> ~/.bashrc'